//
//  KABMallClaListVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/22.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallClaListVC.h"
#import "KABMallProductCCell.h"
#import "KABMallHeaderCRView.h"
#import "KABModel.h"
#import "KABMallShopcartVC.h"
#import "KABMallProDetailVC.h"
#import <MJRefresh.h>
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "GlobalHeader.h"
#import <UIScrollView+EmptyDataSet.h>
#import "KABMallTitleView.h"
#import "ThemeManager.h"

@interface KABMallClaListVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, KABMallTitleViewDelegate>

@property (weak,   nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) KABMallTitleView *mallTitleView;

@property (nonatomic, strong) KABMallProductList *productList;

@end

static NSString *const kReuseCellId = @"KABMallProductCCell";
static NSString *const kReuseHeaderId = @"KABMallHeaderCRView";
static NSInteger const kRequestCosplayListSize = 20;

@implementation KABMallClaListVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.mallTitleView endEditing:YES];
}

- (void)initNavigationBar {
    self.navigationItem.title = self.subTyep_content;
//    self.mallTitleView.titleLabel.text = self.subTyep_content;
    [self.mallTitleView setTextFieldPlaceholder:self.subTyep_content];
    if (self.viewType == KABMallClaListVCTypeSearch) {
        [self.mallTitleView setTextFieldText:self.seachInitText];
    }
    self.navigationItem.titleView = self.mallTitleView;
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mall_classify"] style:UIBarButtonItemStylePlain target:self action:@selector(classifyBtnTapped:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mall_shop_cart"] style:UIBarButtonItemStylePlain target:self action:@selector(shopCartBarBtnTapped:)];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
//    UINib *cRViewNib = [UINib nibWithNibName:kReuseHeaderId bundle:nil];
//    [self.collectionView registerNib:cRViewNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseHeaderId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.emptyDataSetSource = self;
    
    // 下拉刷新
    self.collectionView.mj_header = self.mj_header;
    self.collectionView.mj_footer = self.mj_footer;
    // 请求数据
    [self.collectionView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有相关商品" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.productList.product_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABMallProductCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.item < self.productList.product_list.count) {
        [cell configViewWithProductItem:self.productList.product_list[indexPath.item]];
    }
    return cell;
}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABMallHeaderCRView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseHeaderId forIndexPath:indexPath];
//        header.delegate = self;
//        return header;
//    }
//    
//    return nil;
//}

#pragma mark - <UICollectionViewDelegateFlowLayout>
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    CGFloat width = CGRectGetWidth(self.view.bounds);
//    CGFloat height = width * 244.0 / 375.0;
//    return CGSizeMake(width, height);
//}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 6.0);
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (CGRectGetWidth(self.view.bounds) - 2*14 - 10) / 2.0;
    CGFloat height = width * 257.0 / 169.0;
    return CGSizeMake(width, height);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    KABMallProDetailVC *vc = [[KABMallProDetailVC alloc] init];
    vc.proItem = self.productList.product_list[indexPath.item];
    [self showViewController:vc sender:nil];
}

//- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
//    if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABMallHeaderCRView *headerView = (KABMallHeaderCRView *)view;
//        [headerView bannerViewStartScroll];
//    }
//}
//
//- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
//    if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABMallHeaderCRView *headerView = (KABMallHeaderCRView *)view;
//        [headerView bannerViewStopScroll];
//    }
//}

//#pragma mark - KABMallHeaderCRViewDelegate
//- (void)kABMallHeaderCRView:(KABMallHeaderCRView *)crView didSelectAtIndex:(NSUInteger)index {
//    
//}
//
//- (void)kABMallHeaderCRView:(KABMallHeaderCRView *)crView navViewTapped:(UIView *)view {
//    
//}

#pragma mark - KABMallTitleViewDelegate
- (void)kABMallTitleView:(KABMallTitleView *)view searchBtnTapped:(UIButton *)btn {
    if (self.viewType == KABMallClaListVCTypeSubType) {
        KABMallClaListVC *vc = [[KABMallClaListVC alloc] init];
        vc.subType_id = self.subType_id;
        vc.subTyep_content = @"请输入商品名称";
        vc.viewType = KABMallClaListVCTypeSearch;
        vc.seachInitText = view.inputText;
        [self showViewController:vc sender:nil];
        [self.mallTitleView setTextFieldText:nil];
    } else {
        [self requestProductListWithHeader:YES keyword:view.inputText];
    }
}
- (void)kABMallTitleView:(KABMallTitleView *)view textFieldChanged:(UITextField *)textField {
    if (self.viewType == KABMallClaListVCTypeSearch) {
        [self requestProductListWithHeader:YES keyword:view.inputText];
    }
}

#pragma mark - event response
- (void)shopCartBarBtnTapped:(UIBarButtonItem *)barBtn {
    KABMallShopcartVC *vc = [[KABMallShopcartVC alloc] init];
    [self showViewController:vc sender:nil];
}

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.productList.totalLoad) {
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.collectionView.mj_footer resetNoMoreData];
    }
    
    [self.collectionView reloadData];
}

- (void)collectionViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.collectionView.mj_header endRefreshing];
    } else {
        [self.collectionView.mj_footer endRefreshing];
    }
}

- (void)collectionViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    NSString * keyword = (self.viewType == KABMallClaListVCTypeSearch) ? self.mallTitleView.inputText : nil;
    [self requestProductListWithHeader:isHeader keyword:keyword];
}

- (KABMallProductList *)productListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.productList;
    }
    
    KABMallProductList *temp = [KABMallProductList yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.productList;
    }
    
    if (AddMore && self.productList) {
        [self.productList addMoreWithData:temp];
    } else {
        self.productList = temp;
    }
    return self.productList;
}

#pragma mark - network request
- (void)requestProductListWithHeader:(BOOL)isHeader keyword:(NSString *)keyword {
    NSInteger startIndex = isHeader ? 0 : self.productList.product_list.count;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(startIndex) forKey:@"index"];
    [pars setObject:@(kRequestCosplayListSize) forKey:@"size"];
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    //    [pars setObject:@(sex) forKey:@"sex"];
    if (keyword) {
        [pars setObject:keyword forKey:@"keyword"];
    }
    [pars setObject:@(self.subType_id) forKey:@"sub_type"];
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiProductList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求商品列表返回：%@", responseObject);
        [self collectionViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self productListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求商品列表失败：%@", error);
        [self collectionViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (KABMallTitleView *)mallTitleView {
    if (!_mallTitleView) {
        _mallTitleView = [[KABMallTitleView alloc] init];
        _mallTitleView.bgColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMallSeaBgColor];
        _mallTitleView.textColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMallSeaTextColor];
        _mallTitleView.placeholderColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMallSeaPlaceholderColor];
        _mallTitleView.textFieldTintColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMallSeaTextFieldTintColor];
        _mallTitleView.delegate = self;
    }
    return _mallTitleView;
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
